<template>
  <view class="dashboard-container">
    <!-- 欢迎区域 -->
    <view class="welcome-section">
      <view class="welcome-header">
        <image class="logo" src="/static/images/MEISHEN.png" mode="aspectFit"></image>
        <view class="company-name">美申智控系统</view>
        <view class="company-slogan">智慧环保 · 绿色管理</view>
      </view>
      <view class="welcome-content">
        <view class="welcome-text">
          <view class="greeting">{{ greeting }}，{{ userStore.userInfo?.username || '用户' }}</view>
          <view class="date">{{ currentDate }}</view>
        </view>
        <view class="welcome-avatar">
          <view class="avatar">{{ userStore.userInfo?.username?.charAt(0) || 'U' }}</view>
        </view>
      </view>
    </view>
    
    <!-- 统计卡片 -->
    <view class="stats-section">
      <view class="stats-grid">
        <view class="stat-card" @click="goToDevices">
          <view class="stat-icon" style="color: #52c41a;">🏠</view>
          <view class="stat-content">
            <view class="stat-value">{{ dashboardData.summary?.total_devices || 0 }}</view>
            <view class="stat-label">设备总数</view>
          </view>
        </view>
        
        <view class="stat-card" @click="goToDevices">
          <view class="stat-icon" :class="{ 'text-success': dashboardData.summary?.online_devices > 0 }" style="color: #73d13d;">📡</view>
          <view class="stat-content">
            <view class="stat-value" style="color: #52c41a;">{{ dashboardData.summary?.online_devices || 0 }}</view>
            <view class="stat-label">在线设备</view>
          </view>
        </view>
        
        <view class="stat-card" @click="goToWorkOrders">
          <view class="stat-icon" :class="{ 'text-warning': dashboardData.summary?.pending_work_orders > 0 }" style="color: #faad14;">📋</view>
          <view class="stat-content">
            <view class="stat-value" style="color: #fa8c16;">{{ dashboardData.summary?.pending_work_orders || 0 }}</view>
            <view class="stat-label">待处理工单</view>
          </view>
        </view>
        
        <view class="stat-card" @click="goToAlerts">
          <view class="stat-icon" :class="{ 'text-error': dashboardData.summary?.critical_alerts > 0 }" style="color: #ff4d4f;">⚠️</view>
          <view class="stat-content">
            <view class="stat-value" style="color: #ff4d4f;">{{ dashboardData.summary?.critical_alerts || 0 }}</view>
            <view class="stat-label">严重告警</view>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 功能模块 -->
    <view class="modules-section">
      <view class="section-title">功能模块</view>
      <view class="modules-grid">
        <view class="module-item" @click="goToDevices">
          <view class="module-icon" style="color: #52c41a;">🏠</view>
          <view class="module-name">设备管理</view>
        </view>
        
        <view class="module-item" @click="goToWorkOrders">
          <view class="module-icon" style="color: #73d13d;">📝</view>
          <view class="module-name">工单管理</view>
        </view>
        
        <view class="module-item" @click="goToAlerts">
          <view class="module-icon" style="color: #faad14;">🔔</view>
          <view class="module-name">告警管理</view>
        </view>
        
        <view class="module-item" @click="goToReports" v-if="userStore.hasRole('manager')">
          <view class="module-icon" style="color: #52c41a;">📊</view>
          <view class="module-name">数据报表</view>
        </view>
      </view>
    </view>
    
    <!-- 最近动态 -->
    <view class="activity-section" v-if="realTimeData">
      <view class="section-title">最近动态</view>
      
      <!-- 最近告警 -->
      <view class="activity-card" v-if="realTimeData.recent_alerts?.length > 0">
        <view class="activity-header">
          <view class="activity-title">最新告警</view>
          <view class="activity-more" @click="goToAlerts" style="color: #52c41a;">查看更多</view>
        </view>
        <view class="activity-list">
          <view
            v-for="alert in realTimeData.recent_alerts.slice(0, 3)"
            :key="alert.id"
            class="activity-item"
            @click="goToAlertDetail(alert.id)"
          >
            <view class="activity-content">
              <view class="activity-text">{{ alert.title }}</view>
              <view class="activity-time">{{ formatRelativeTime(alert.created_at) }}</view>
            </view>
            <view class="activity-badge" :class="`badge-${alert.level}`">
              {{ getAlertLevelText(alert.level) }}
            </view>
          </view>
        </view>
      </view>
      
      <!-- 最近工单 -->
      <view class="activity-card" v-if="realTimeData.recent_work_orders?.length > 0">
        <view class="activity-header">
          <view class="activity-title">最新工单</view>
          <view class="activity-more" @click="goToWorkOrders" style="color: #52c41a;">查看更多</view>
        </view>
        <view class="activity-list">
          <view
            v-for="workOrder in realTimeData.recent_work_orders.slice(0, 3)"
            :key="workOrder.id"
            class="activity-item"
            @click="goToWorkOrderDetail(workOrder.id)"
          >
            <view class="activity-content">
              <view class="activity-text">{{ workOrder.title }}</view>
              <view class="activity-time">{{ formatRelativeTime(workOrder.created_at) }}</view>
            </view>
            <view class="activity-badge" :class="`badge-${workOrder.priority}`">
              {{ getWorkOrderPriorityText(workOrder.priority) }}
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 自定义底部导航 -->
    <SimpleTabNav :currentTab="0" />
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { onShow, onPullDownRefresh } from '@dcloudio/uni-app'
import { useUserStore } from '../../src/store/user'
import { useAppStore } from '../../src/store/app'
import { getDashboardOverview, getRealTimeData, type DashboardOverview, type RealTimeData } from '../../src/api/dashboard'
import { formatRelativeTime, getAlertLevelText, getWorkOrderPriorityText } from '../../src/utils'
import SimpleTabNav from '@/components/SimpleTabNav.vue'

const userStore = useUserStore()
const appStore = useAppStore()

// 数据
const dashboardData = ref<DashboardOverview>({} as DashboardOverview)
const realTimeData = ref<RealTimeData | null>(null)
const loading = ref(false)

// 问候语
const greeting = computed(() => {
  const hour = new Date().getHours()
  if (hour < 6) return '夜深了'
  if (hour < 12) return '早上好'
  if (hour < 18) return '下午好'
  return '晚上好'
})

// 当前日期
const currentDate = computed(() => {
  const date = new Date()
  const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
  const month = date.getMonth() + 1
  const day = date.getDate()
  const weekday = weekdays[date.getDay()]
  
  return `${month}月${day}日 ${weekday}`
})

// 页面显示时刷新数据
onShow(() => {
  loadData()
})

// 页面挂载时加载数据
onMounted(() => {
  loadData()
})

// 下拉刷新
onPullDownRefresh(() => {
  loadData().finally(() => {
    uni.stopPullDownRefresh()
  })
})

// 加载数据
const loadData = async () => {
  if (loading.value) return
  
  try {
    loading.value = true
    
    const [overviewResponse, realTimeResponse] = await Promise.all([
      getDashboardOverview().catch(err => {
        console.error('获取概览数据失败:', err)
        return { data: {} }
      }),
      getRealTimeData().catch(err => {
        console.error('获取实时数据失败:', err)
        return { data: null }
      })
    ])
    
    dashboardData.value = overviewResponse.data || {}
    realTimeData.value = realTimeResponse.data
    
  } catch (error) {
    console.error('加载仪表盘数据失败:', error)
    appStore.showError('数据加载失败')
  } finally {
    loading.value = false
  }
}

// 导航方法
const goToDevices = () => {
  uni.navigateTo({
    url: '/pages/devices/index'
  })
}

const goToWorkOrders = () => {
  uni.navigateTo({
    url: '/pages/work-orders/index'
  })
}

const goToAlerts = () => {
  uni.navigateTo({
    url: '/pages/alerts/index'
  })
}

const goToReports = () => {
  // 报表页面暂未实现
  appStore.showToast('功能开发中')
}

const goToAlertDetail = (id: number) => {
  uni.navigateTo({
    url: `/pages/alerts/detail?id=${id}`
  })
}

const goToWorkOrderDetail = (id: number) => {
  uni.navigateTo({
    url: `/pages/work-orders/detail?id=${id}`
  })
}
</script>

<style lang="scss" scoped>
.dashboard-container {
  background-color: #f5f5f5;
  min-height: 100vh;
}

.welcome-section {
  background: linear-gradient(135deg, #52c41a 0%, #73d13d 50%, #95de64 100%);
  padding: 20rpx 32rpx 40rpx;
  position: relative;
  
  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(45deg, rgba(255,255,255,0.1) 0%, rgba(255,255,255,0.05) 100%);
  }
  
  .welcome-header {
    text-align: center;
    margin-bottom: 32rpx;
    position: relative;
    z-index: 1;
    
    .logo {
      width: 100rpx;
      height: 100rpx;
      border-radius: 50rpx;
      background: rgba(255, 255, 255, 0.95);
      padding: 12rpx;
      margin-bottom: 12rpx;
      box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
    }
    
    .company-name {
      font-size: 36rpx;
      font-weight: bold;
      color: #ffffff;
      text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.2);
      margin-bottom: 6rpx;
    }
    
    .company-slogan {
      font-size: 22rpx;
      color: rgba(255, 255, 255, 0.9);
      font-weight: 500;
    }
  }
  
  .welcome-content {
    display: flex;
    align-items: center;
    justify-content: space-between;
    position: relative;
    z-index: 1;
    
    .welcome-text {
      flex: 1;
      
      .greeting {
        font-size: 28rpx;
        font-weight: bold;
        color: #ffffff;
        margin-bottom: 6rpx;
        text-shadow: 0 1rpx 3rpx rgba(0, 0, 0, 0.2);
      }
      
      .date {
        font-size: 22rpx;
        color: rgba(255, 255, 255, 0.85);
      }
    }
    
    .welcome-avatar {
      .avatar {
        width: 70rpx;
        height: 70rpx;
        border-radius: 50%;
        background: linear-gradient(135deg, #389e0d, #52c41a);
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 28rpx;
        font-weight: bold;
        color: #ffffff;
        border: 2rpx solid rgba(255, 255, 255, 0.3);
        box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);
      }
    }
  }
}

.stats-section {
  padding: 0 32rpx;
  margin-top: -20rpx;
  position: relative;
  z-index: 2;
  
  .stats-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 24rpx;
    
    .stat-card {
      background: #ffffff;
      border-radius: 16rpx;
      padding: 32rpx 24rpx;
      box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
      display: flex;
      align-items: center;
      
      .stat-icon {
        font-size: 48rpx;
        margin-right: 24rpx;
      }
      
      .stat-content {
        flex: 1;
        
        .stat-value {
          font-size: 40rpx;
          font-weight: bold;
          color: #262626;
          line-height: 1;
          margin-bottom: 8rpx;
        }
        
        .stat-label {
          font-size: 24rpx;
          color: #8C8C8C;
        }
      }
    }
  }
}

.modules-section {
  padding: 48rpx 32rpx 32rpx;
  
  .section-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #262626;
    margin-bottom: 32rpx;
  }
  
  .modules-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 24rpx;
    
    .module-item {
      background: #ffffff;
      border-radius: 16rpx;
      padding: 32rpx 16rpx;
      text-align: center;
      box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
      
      .module-icon {
        font-size: 48rpx;
        margin-bottom: 16rpx;
      }
      
      .module-name {
        font-size: 24rpx;
        color: #262626;
      }
      
      &:active {
        background-color: #f5f5f5;
      }
    }
  }
}

.activity-section {
  padding: 32rpx;
  
  .section-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #262626;
    margin-bottom: 32rpx;
  }
  
  .activity-card {
    background: #ffffff;
    border-radius: 16rpx;
    margin-bottom: 24rpx;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
    
    .activity-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 24rpx 24rpx 16rpx;
      border-bottom: 1rpx solid #f0f0f0;
      
      .activity-title {
        font-size: 28rpx;
        font-weight: bold;
        color: #262626;
      }
      
      .activity-more {
        font-size: 24rpx;
        color: #007AFF;
      }
    }
    
    .activity-list {
      .activity-item {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 20rpx 24rpx;
        border-bottom: 1rpx solid #f5f5f5;
        
        &:last-child {
          border-bottom: none;
        }
        
        &:active {
          background-color: #fafafa;
        }
        
        .activity-content {
          flex: 1;
          min-width: 0;
          
          .activity-text {
            font-size: 28rpx;
            color: #262626;
            margin-bottom: 8rpx;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
          
          .activity-time {
            font-size: 22rpx;
            color: #8C8C8C;
          }
        }
        
        .activity-badge {
          font-size: 20rpx;
          padding: 4rpx 12rpx;
          border-radius: 12rpx;
          margin-left: 16rpx;
          
          &.badge-low { background-color: #f6ffed; color: #52c41a; }
          &.badge-medium { background-color: #e6f7ff; color: #1890ff; }
          &.badge-high { background-color: #fff7e6; color: #faad14; }
          &.badge-urgent { background-color: #fff2f0; color: #ff4d4f; }
          &.badge-info { background-color: #e6f7ff; color: #1890ff; }
          &.badge-warning { background-color: #fff7e6; color: #faad14; }
          &.badge-error { background-color: #fff2f0; color: #ff4d4f; }
          &.badge-critical { background-color: #f9f0ff; color: #722ed1; }
        }
      }
    }
  }
}

.text-success { color: #52c41a; }
.text-warning { color: #faad14; }
.text-error { color: #ff4d4f; }
</style>